package com.geekbang.work.lock;

import redis.clients.jedis.Jedis;

import java.util.Arrays;

/**
 * @author nhsoft.lul
 */
public class LuaApplication {
    private String host = "127.0.0.1";
    private int port = 6379;
    private Jedis jedis = new Jedis(host, port);



    public void lock(String key, String value) {
        Long res = jedis.setnx(key, value);
        jedis.expire(key, 1);
        if (res == 1) {
            System.out.println(String.format("%s获取锁成功", value));
            service(key, value);
        } else {
            System.out.println(String.format("%s获取锁失败", value));
        }
    }

    public void release(String key, String value) {
        String luaScript = "if redis.call('get',KEYS[1]) == ARGV[1] then " + "return redis.call('del',KEYS[1]) else return 0 end";
        Long evalRes = (Long) jedis.eval(luaScript, Arrays.asList(key), Arrays.asList(value));
        if(evalRes == 1){
            System.out.println(String.format("%s释放锁成功", value));
        }else{
            System.out.println(String.format("%s释放锁失败", value));
        }
    }

    public void service(String key, String value) {
        //模拟业务处理
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            release(key, value);
        }
    }


    public static void main(String[] args) {

        Runnable runnable1 = () -> {
            LuaApplication demo = new LuaApplication();
            demo.lock("lock", "D1");
        };
        new Thread(runnable1).start();

        Runnable runnable2 = () -> {
            LuaApplication demo = new LuaApplication();
            demo.lock("lock", "D2");
        };
        new Thread(runnable2).start();
    }

}
